package com.youlu.campus.service.activity.impl;

import com.alibaba.fastjson.JSON;
import com.mongodb.client.result.DeleteResult;
import com.youlu.campus.base.exception.BusinessException;
import com.youlu.campus.entity.ActivityQaInfo;
import com.youlu.campus.entity.ActivityQaRule;
import com.youlu.campus.entity.VO.req.ActivityQaRuleQueryVO;
import com.youlu.campus.service.activity.ActivityQaRuleService;
import com.youlu.campus.service.activity.ActivityTaskService;
import com.youlu.campus.service.qa.ActivityQaInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.repository.support.PageableExecutionUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class ActivityQaRuleServiceImpl implements ActivityQaRuleService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private ActivityTaskService activityTaskService;
    @Autowired
    private ActivityQaInfoService activityQaInfoService;

    @Override
    public ActivityQaRule match(String activityId, String activityQaInfoId, Integer score) {
        log.info(":>>> 开始匹配答题规则:{},{},{}", activityId, activityQaInfoId, score);
        if (StringUtils.isBlank(activityId) || Objects.isNull(score)) {
            log.error(":>>> 答题规则匹配参数错误:无配置的规则");
            return null;
        }
        Query query = new Query().addCriteria(Criteria.where("activityId").is(activityId));
        if (StringUtils.isNotBlank(activityQaInfoId)) {
            query.addCriteria(Criteria.where("activityQaInfoId").is(activityQaInfoId));
        }
        query.with(Sort.by(Sort.Order.desc("priority")));
        List<ActivityQaRule> datas = mongoTemplate.find(query, ActivityQaRule.class);
        if (CollectionUtils.isEmpty(datas)) {
            log.error(":>>> 答题规则匹配错误:无配置的规则");
            return null;
        }
        int i = 1;
        for (ActivityQaRule data : datas) {
            log.info(":>>> 开始匹配答题证书规则序号:{},:{}", i, JSON.toJSON(data));
            if (StringUtils.isBlank(data.getInviteOperatorType())) {
                log.info(":>>>  操作类型为空:{}", data.getId());
                continue;
            }
            //       section,equals,leftInterval,rightInterval
            //        return (x < y) ? -1 : ((x == y) ? 0 : 1);
            switch (data.getInviteOperatorType()) {
                case "section":
                    if (Objects.nonNull(data.getQaStart()) && Objects.nonNull(data.getQaEnd())) {
                        if ((score.compareTo(data.getQaStart()) != -1) && (score.compareTo(data.getQaEnd()) != 1)) {
                            log.info(":>>> 匹配上规则:{}", JSON.toJSONString(data));
                            return data;
                        } else {
                            log.error(":>>> 规则没有匹配:{}", data.getId());
                        }
                    }
                    break;
                case "equals":
                    if (Objects.nonNull(data.getQaEqu())) {
                        if (score.compareTo(data.getQaEqu()) == 0) {
                            log.info(":>>> 匹配上规则:{}", JSON.toJSONString(data));
                            return data;
                        }
                    }
                    break;
                case "leftInterval":
                    if (Objects.nonNull(data.getQaStart())) {
                        if (score.compareTo(data.getQaStart()) != 1) {
                            log.info(":>>> 匹配上规则:{}", JSON.toJSONString(data));
                            return data;
                        }
                    }
                    break;
                case "rightInterval":
                    if (Objects.nonNull(data.getQaEnd())) {
                        if (score.compareTo(data.getQaEnd()) != -1) {
                            log.info(":>>> 匹配上规则:{}", JSON.toJSONString(data));
                            return data;
                        }
                    }
                    break;
                default:
                    continue;
            }
            i++;
        }
        return null;
    }

    @Override
    public String getQaCa(String activityId, String activityQaInfoid, Integer score) {
        ActivityQaRule activityQaRule = this.match(activityId, activityQaInfoid, score);
        if (Objects.isNull(activityQaRule)) {
            log.error(":>>> 活动:{},题库:{},得分:{} 匹配的答题规则为空,设置为暂无证书", activityId, activityQaInfoid, score);
            return "暂无证书";
        }
        return activityQaRule.getCaName();
    }

    @Override
    public Page<ActivityQaRule> list(ActivityQaRuleQueryVO request) {
        log.info(":>>> 开始获取活动答题规则列表:{}", JSON.toJSONString(request));
        if (Objects.isNull(request) || StringUtils.isBlank(request.getActivityQaInfoId())) {
            log.error(":>>> 任务ID为空");
            throw new BusinessException("任务列表参数错误");
        }
        Query query = new Query().addCriteria(Criteria.where("activityQaInfoId").is(request.getActivityQaInfoId()));
        Long count = mongoTemplate.count(query, ActivityQaRule.class);
        log.info(":>>> 活动答题任务规则的数量:{}，查询条件:{}", count, JSON.toJSON(query));
        PageRequest pageRequest = PageRequest.of(request.getPage() - 1, request.getPageSize());
//        query.with(new Sort(Sort.Direction.DESC, "priority"));
        Sort sort=Sort.by(Sort.Direction.DESC, "priority");
        query.with(sort);
        List<ActivityQaRule> orderPOS = mongoTemplate.find(query.with(pageRequest), ActivityQaRule.class);
        final Long c = count;
        return PageableExecutionUtils.getPage(orderPOS, pageRequest, () -> c);
    }

    @Override
    public boolean create(ActivityQaRule req) {
        if (Objects.isNull(req) || StringUtils.isBlank(req.getActivityQaInfoId())) {
            log.error(":>>> 新增任务规则错误");
            throw new BusinessException("新增任务规则错误");
        }
        ActivityQaInfo activityQaInfo = activityQaInfoService.findOne(req.getActivityQaInfoId());
        req.setCreatedTime(new Date());
        req.setId(null);
        req.setActivityId(activityQaInfo.getActivityId());
        req = mongoTemplate.insert(req);
        if (Objects.nonNull(req)) {
            return true;
        }
        return false;
    }

    @Override
    public boolean update(ActivityQaRule req) {
        if (Objects.isNull(req) || StringUtils.isBlank(req.getId()) || StringUtils.isBlank(req.getActivityQaInfoId())) {
            log.error(":>>> 修改题库规则参数错误");
            throw new BusinessException("修改题库规则参数错误");
        }
        req.setUpdatedTime(new Date());
        mongoTemplate.save(req);
        return true;
    }


    @Override
    public boolean delete(String id) {
        Query query = this.getQueryId(id);
        DeleteResult result = mongoTemplate.remove(query, ActivityQaRule.class);
        return result.getDeletedCount() > 0 ? true : false;
    }

    @Override
    public ActivityQaRule findOne(String id) {
        Query query = new Query().addCriteria(Criteria.where("id").is(id));
        return mongoTemplate.findOne(query, ActivityQaRule.class);
    }

    private Query getQueryId(String id) {
        if (StringUtils.isBlank(id)) {
            log.error(":>>> 参数ID为空");
            throw new BusinessException("参数ID为空");
        }
        Query query = new Query().addCriteria(Criteria.where("id").is(id));
        return query;
    }
}
